﻿

using System.Text;

using NLog;
using System.Net;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.IO;

namespace tuyaxia.MissJane
{

    public class Weather
    {
      
        public static JObject o=null;
        Logger log;//nlog
        public Weather(string city)
        {
            log = LogManager.GetCurrentClassLogger();//nlog
            getWeather(city);

        }

        public  void getWeather(string city)
        {
            string retString="";
            string url = "https://api.seniverse.com/v3/weather/now.json?key=ypzoml2erri8v24d&location=" + city + "&language=zh-Hans&unit=c";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            try {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            }
            catch {
                
                log.Info("网络天气预报获取失败,请手动输入.");
                return; }
            o = JObject.Parse(retString);


        }


        public string getWeatherType()
        {

            if (o!=null&&o.Property("results")!= null) return o["results"][0]["now"]["text"].ToString();
            else
            {
                return "晴";
            }
        }
        public string getTemperature()
        {
            if (o != null && o.Property("results") != null) return o["results"][0]["now"]["temperature"].ToString();
            else return ""; 
        }

    }

}



 
